import Auth from '../api/auth'
import store from '@/store'
// const parseErrorCode = error => Promise.reject(error)

export default axios => {
  const { apiHost = '' } = window.chatwootConfig || {}
  const wootApi = axios.create({ baseURL: `${apiHost}/` })
  // Add Auth Headers to requests if logged in
  if (Auth.hasAuthCookie()) {
    const {
      'accessToken': accessToken,
    } = Auth.getAuthData()
    Object.assign(wootApi.defaults.headers.common, {
      'Authorization': `Bearer ${accessToken}`,
    })
    // const {
    //   'access-token': accessToken,
    //   'token-type': tokenType,
    //   client,
    //   expiry,
    //   uid,
    // } = Auth.getAuthData()
    // Object.assign(wootApi.defaults.headers.common, {
    //   'access-token': accessToken,
    //   'token-type': tokenType,
    //   client,
    //   expiry,
    //   uid,
    // })
  }
  // Response parsing interceptor
  wootApi.interceptors.response.use(
    response => response,
    error => {
      // if has response show the error
      if (error.response.status === 401) {
        // if you ever get an unauthorized, logout the user
        store.dispatch('logout')
        window.location = '/login'
        // you can also redirect to /login if needed !
      }
      return Promise.reject(error)
    }
  )
  return wootApi
}
